package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.Order;
import com.qf.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * @author zhaojian
 */
@Controller
@RequestMapping("/json")
public class JsonDemoController {

    /**
     * 跳转到json演示页面
     * @return
     */
    @RequestMapping("/jsonDemo")
    public String jsonDemo() {
        System.out.println("======JsonDemoController========jsonDemo方法被执行======");
        return "jsonDemo";
    }

    /**
     * 接口json格式字符串, 并自动转换成java对象
     * 将java对象自动转换成json格式字符串返回给页面
     * @param user
     * @return
     */
    @RequestMapping("/test1")
    @ResponseBody
    public User demo1(@RequestBody User user) {
        user.setBirthday(new Date());

        //手动使用阿里的fastJson包进行json格式转换
        //parseObject转换成单个对象
        String  jsonStr = "{\"id\": 1, \"name\": \"我是订单\"}";
        Order order = JSON.parseObject(jsonStr, Order.class);
        System.out.println("======" + order);

        //手动使用阿里的fastJson包进行json格式转换
        //parseArray转换成集合对象
        String jsonStrList = "[{\"id\": 1, \"name\": \"我是订单1\"}, " +
                "{\"id\": 2, \"name\": \"我是订单2\"}," +
                "{\"id\": 3, \"name\": \"我是订单3\"}]";
        List<Order> orderList = JSON.parseArray(jsonStrList, Order.class);
        System.out.println("========" + orderList);

        System.out.println("=======" + user);
        return user;
    }
}
